<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<!--[if lt IE 7 ]><html class="ie ie6"><![endif]-->
<!--[if IE 7 ]><html class="ie ie7"><![endif]-->
<!--[if IE 8 ]><html class="ie ie8"><![endif]-->
<!--[if IE 9 ]><html class="ie ie9"><![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--><html><!--<![endif]-->
<head>
	<meta charset="utf-8">
	<meta name="renderer" content="webkit" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="initial-scale=1,minimum-scale=1" />
	<title>九宫格设置</title>
    <c:import url="${appRoot}/public/head-tag.jsp"/>
    <style>
        /* 必需 */
        .sort-enter {
          transition: all .3s ease;
          background-color: #eee;
        }
        .examplediv{
        	position: absolute;
        	top:380px;
        	right: 0;
        }
        .text-datetime{
			width:215px;
		}
		.xiuxiu-upload-container,div.xiuxiu-upload {
		    width: 310px;
    		height: 300px;
		}
		li img{
			/*display: inline-block;*/
			float: left;
			padding: 5px;
			width: 20px;
			height: 20px;
			text-align: left;
		}
    </style>
</head>
<body>
	
    <c:import url="${appRoot}/public/header.jsp"/>
    
    <section class="container">
    	
	    <c:set var="sidebar" scope="request" value="content"/>
	    <c:set var="navbar" scope="request" value="activity"/>
	    <c:import url="${appRoot}/public/sidebar.jsp"/>
		
    	<div class="content" id="app">
    		<div class="content-top">
                <h3 class="content-title">
                    <div class="bread">
                        <a href="#">九宫格</a>
                        <span>&gt;</span>
                        <span v-text=" form.actionId ? '编辑': '新增' "></span>
                    </div>
                </h3>
    		</div>
    		<div class="content-main">
    			<div class="block-content">
                        <div class="form-block" >
                            
        			        <form action="null" data-form="one" method="post" goback="/Manager/web/action/listPage">
                                <div class="form-row">
                                    <span class="row-label">转盘名称：</span>
                                    <div class="row-content">
                                        <input name="title" type="text" class="text" v-model="form.title" iname="转盘名称"/>
                                    </div>
                                </div>
							        
                                <div class="form-row">
                                    <span class="row-label">抽奖资格：</span>
                                    <div class="row-content">
                                        <div class="row-value">
                                            <input type="radio" id="limit-0" name="limits" value="0"  v-model="actionPrize.winninglimit" :true-value="0"/>
                                            <label for="limit-0">不限</label>
                                        </div><br/>
                                        
                                        <div class="row-value">
                                            <input type="radio" id="limit-1" name="limits" value="1"  v-model="actionPrize.winninglimit"  :true-value="1"/ >
                                            <label for="limit-1">限报名用户</label>
                                            <template v-if="actionPrize.winninglimit==1">
                                                <span v-if="actionPrize.relation_info">
                                                       : 参加过【<a href="javascript:;" @click="chooseAction"  v-text="actionPrize.relation_info" class="action-link"></a>】的用户
                                                </span>
                                                <span v-else>
                                                       <a href="javascript:;" @click="chooseAction" class="action-link" >选择活动</a>
                                                </span>
                                                <input type="hidden" iname="关联活动" irequired="true" v-model="actionPrize.relation_id"  name="relationid"/>
                                            </template>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="form-row">
									<span class="row-label">设置轮播：</span>
									<div class="row-content">
										<div class="row-value">
											<input type="checkbox" name="istop" id="category_2" value="1" v-model="form.loopStatus" :true-value="1"/>
											<label for="category_2">设置为轮播</label>
										</div>
									</div>
								</div>
                                
                                <div class="form-row">
                                    <span class="row-label">限制次数：</span>
                                    <div class="row-content">
                                        <input name="availabletimes" type="text" class="text" v-model="actionPrize.available_times" placeholder="每人每天最多抽奖次数，不填不限制" iname="限制次数"/>
                                    </div>
                                </div>
                                <div class="form-row">
                                    <span class="row-label">奖项配置：</span>
                                    <div class="row-content" style="width: 80%;">
                                        <table class="table">
                                            <thead>
                                                <tr>
                                                    <th style="width:10%">位置</th>
                                                    <th style="width:20%">奖品图片</th>
                                                    <th style="width:20%">奖项描述</th>
                                                    <th style="width:10%">中奖概率</th>
                                                    <th style="width:10%">中奖限制</th>
                                                    <th style="width:10%">剩余奖品</th>
                                                    <th style="width:20%">操作</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr v-for="item in prizeItem">
													<td v-text="item.prizeid" ></td>
													<td><img :src="showImage(item.thumb)" style="width: 20px;height: 20px;"/></td>
													<td v-text="item.info" ></td>
													<td v-text="item.winningprobability" ></td>
													<td v-text="item.winninglimit" ></td>
													<td v-text="item.winningnumber" ></td>
													<td><a class="action-link" @click="editItem(item)"  href="javascript:;">编辑</a></td>
												</tr>
                                            </tbody>
                                        </table>
                                        <input type="hidden" name="items" value="{{prizeItem | json}}"/>
                                    </div>
                                </div>
                               
                                <div class="examplediv">
                                    <p class="value-note" style="margin-left: 10%;">转盘位置示例</p>
                                	<div class="row-content" style="width: 110px;">
                                		<ul>
                                			<li v-for="item in prizeItem">
                                				<template v-if="$index==3">
	                                				<img :src="showImage(prizeItem[$index].thumb)" /><img :src="showImage("")"/>
                                				</template>
                                				<template v-else>
    	                            				<img :src="showImage(prizeItem[$index].thumb)"/>
                                				</template>
                                			</li>
										</ul>
                                    </div>
                                </div>
	                            <div class="form-row">
									<span class="row-label">活动图片：</span>
									<div class="row-content">
										<div  xx-upload class="xiuxiu-upload-container">
											<textarea type="config" style="display:none;" v-text="getImageConfig(form.thumb) | json"></textarea>
										</div>
										<p class="value-note">图片规格：750x360</p>
									</div>
								</div>
	                            	
		                            <div class="form-row">
										<span class="row-label">抽奖时间：</span>
										<div class="row-content">									 	
											<input type="text" name="applyStartTime" v-model="form.applyStartTime" value="2016-03-12 07:00" class="text text-datetime" datepicker="datetime" iname="活动起始时间" itip="请选择活动起始时间" placeholder="活动起始时间" />
											<span>至</span>
											<input type="text" name="applyEndTime" v-model="form.applyEndTime"  value="2016-03-20 10:45"  class="text text-datetime" datepicker="datetime" iname="活动结束时间" itip="请选择活动结束时间" placeholder="活动结束时间" />
										</div>
									</div>
		                            
		                            <div class="form-row">
										<span class="row-label">介绍：</span>
											<div class="row-content">
												<textarea name="intro" rteditor class="textarea" iname="活动介绍"   v-model="form.intro" style="width:100%;height: 300px;border: 0px solid #B8B8B8;"></textarea>
											</div>
									</div>
                            </form>
                            <div class="form-row form-row-btn">
                                <input type="hidden" name="type" value="{{pageType}}">
                                <input type="hidden" name="appId" value="{{appId}}">
                                <button @click="save()" class="btn btn-default btn-large">保存</button>
                            </div>
                </div>
    		</div>
    	</div>
    </section>
    
    <script type="text/template" id="field/edit" title="字段编辑">
        <form>
            <div class="form-row">
                <span class="row-label">奖品位置：</span>
                <div class="row-content">
                    <select name="prizeid" v-model="prizeid" class="select">
                    {{each locNum as item1 i}}
                    	<option value={{i+1}} {{if i+1==prizeid}} selected="selected" {{/if}}>{{i+1}}</option>
                    {{/each}}
                    </select>
                </div>
            </div>
            <div class="form-row">
                <span class="row-label">奖项图片：</span>
            	<div class="row-content">
                    <div class="file-container">
                        <uploader :config="uploader" ></uploader>
                        <p class="value-note">推荐规格：200x200</p>
                    </div>
            	</div>
        	</div>
            <div class="form-row">
                <span class="row-label" >奖项描述：</span>
                <div class="row-content">
                    <input type="text" class="text" name="info" v-model="info"  {{if !info}} value="" {{else}} value={{info}} {{/if}}   placeholder="奖项名称描述，不超过6个字"  iname="奖项描述"/>
                </div>
            </div>
            <div class="form-row">
                <span class="row-label">中奖概率：</span>
                <div class="row-content">
                    <input type="text" class="text" name="winningprobability" {{if !winningprobability}} value="" {{else}} value={{winningprobability}} {{/if}}  placeholder="可抽中的奖品总数，抽完之后中奖率为0" irequired="false"  iname="奖品数量"/>%
                </div>
            </div>
            <div class="form-row">
                <span class="row-label">中奖限制：</span>
                <div class="row-content">
                    <input type="text" class="text" name="winninglimit" v-model="winninglimit" {{if !winninglimit}} value="" {{else}} value={{winninglimit}} {{/if}}   placeholder="中奖几率总和为100" irequired="false"  iname="中奖概率"/>次
                </div>
            </div>
            
            <div class="form-row">
                <span class="row-label">剩余奖品：</span>
                <div class="row-content">
                    <input type="text" class="text" name="winningnumber" v-model="winningnumber"  {{if !winningnumber}} value="" {{else}} value={{winningnumber}} {{/if}}  placeholder="每个用户最多抽中此奖项多少次，不填不限制" irequired="false"  iname="中奖限制"/>件
                </div>
            </div>
        </form>
    </script>
    
    <script type="text/template" id="content/item/select" title="选择">
        <style>
            .block-item-select .content-item-block{
                height:250px;
                overflow-y:scroll;
            }
        </style>
        <section class="content-block block-item-select">
            <div class="content-item" data-template="content/list/item">
                <div class="content-item-top">
                    <form action="{{api}}" method="get" autocomplete="off">
                        <input placeholder="输入关键字搜索" type="text" name="sw" class="text"/>
                        <input type="submit" class="btn btn-default" value="搜索" />
                    </form>
                </div>
                <div class="content-item-block scrollbar">
                    <table class="table">
                        <thead>
                            <tr>
                                <th style="width:90%"></th>
                                <th style="width:10%"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td colspan="2" class="align-center">
                                    <div class="loading">加载中...</div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </section>
    </script>
    
     <script type="text/template" id="content/list/item">
        {{if  !code }}
            <tr><td colspan="2">请求错误！</td></tr>
        {{else if code!=200}}
            <tr><td colspan="2">{{msg || '查询错误！'}}</td></tr>
        {{else if !data.list || data.list.length==0}}
            <tr><td colspan="2">没有记录！</td></tr>
        {{else}}
            {{each data.list as item}}
                <tr>
                    <td class="align-left">
                        <input id="item_{{item.id || item.actionId}}" data-params="{{item | pick:'actionId:id,title:name' | toJSON}}" value="{{item.id || item.actionId}}" type="radio" name="content_item" />
                        <label for="item_{{item.id || item.actionId}}">{{item.title}}</label>
                    </td>
                </tr>
            {{/each}}
        {{/if}}
    </script>
	
   <script src="/pages/assets/js/require.all.js"></script>
   <script>
        requirejs([
            'vue', 
            'vue.components', 
            'artTemplate', 
            'artDialog',  
            "moment",
            
            'vender.actions',
            'utils.search', 
            
            'vender.xxupload', 
            'vender.rteditor', 
            'vender.datetimepicker',
            
            'jquery.md5', 
            'jquery.formcheck', 
            'jquery.ajaxsubmit',
            'jquery.common',
        ], 
        function(Vue, VueComponents, template, dialog, moment, Action, Search, XXUpload, RichTextEditor, DateTimePicker){
    		
    		var search = new Search().getParams()
            var isEdit = !!search.id;
            
            Action.extend({
				'form.relate':'/Manager/web/action/listSearch?status=1',
				'form.detail' : '/Manager/web/action/detail?id={data}',
				'form.add' : '/Manager/web/action/addSave',
       			'form.update' : '/Manager/web/action/updateSave',
            })

            var PageType = Field.Plugins.LOTTERY_9GRID;

            var App={
                alert : function(){
                  if(arguments[0])
                  alert(arguments[0]);
                },
				chooseContentItem:function(){
                    
                    var dtd = $.Deferred();
                    
                    var id="content/item/select";
                    
                    var title=document.getElementById(id).title;
                    var data={
                        api:Action.get('form.relate')
                    }
                    
                    var content=template(id, data);
                    var idialog=dialog({
                        id : id,
                        title:title,
                        content:content,
                        onshow:function(){
                            this.getContent().find('[data-template]').ajaxLoad({
                                dataFilter:function(res){
                                    return res
                                }
                            })
                        },
                        onclose:function(){
                            dtd.reject();
                            this.remove();
                        },
                        zIndex: 5,
                        width:500,
                        button:[
                            {
                                id:"cancel",value:"取消"
                            },
                            {
                                id:"ok",value:"确定",
                                autofocus:true,
                                callback:function(){
                                    var $input=this.getContent().find("input:checked");
                                    if(!$input.length) {
                                        alert('请选择！')
                                        return false;
                                    }
                                    var params = $input.data('params');
                                    dtd.resolve(params)
                                }
                            }
                        ]
                    }).showModal();
                    
                    return dtd;
                },
                showFieldEditor:function(data){
                    var app = this;
                    var dtd = $.Deferred();
                    data.locNum=new Array(8);//创建8个位置
                    var id = 'field/edit';

					var title="奖项编辑";
					
					var content=template(id, data);
                    var idialog=dialog({
                        id : id,
                        title:title,
                        content:content,
                        onclose:function(){
                            this.remove();
                        },
                        onshow:function(){
                            var el = this.getContent().get(0);
                            new Vue({
                                el:el,
                                components: {'uploader':VueComponents.uploader },
                                computed:{
                                	test:function(){
                                		return this.uploader.uploadUrl;
                                	}
                                },
                                data:function(){
	                                var files=[];
	                                if(data.prizeimage) files = [{
	                               		id:1,
	                               		file:data.thumb
	                                }];
                                    return {
                                        form:data,
                                        uploader:{
		                                     files:files,
		                                     name:'thumb',
                                             maxFiles:1,
		                                     uploadUrl: Action.get('qiniu.image.upload'),
		                                     onUploaded:function(result){
		                                         return result.key
		                                     },
		                                     beforeUpload:function(resolve){
		                                     	
		                                    	 if(app.qiniuUploadToken) return resolve({token:app.qiniuUploadToken});
		                                         
		                                     	  var url = Action.get('qiniu.upload.token');
		                                     	  $.getJSON(url, function(result){
		                                     		  if(result.token) {
		                                     			  resolve({
		                                         			  token:result.token
		                                         		  })
		                                         		  app.qiniuUploadToken = result.token;
		                                     		  }
		                                     		  else{
		                                     			  Modal.alert('上传失败', result.msg)
		                                     		  }
		                                     	  }).fail(function(e, type, msg){
		                                     		  Modal.alert(type + msg)
		                                     	  })
		                                     },
		                                     showImage:function(img){
		                                        if(/^(http(s)?|\/\/)/.test(img)) return img;
		                                        return Action.get('image.logo', img)
		                                     }
		                                }
                                    }
                                }
                            })
                        },
                        button:[
                            {
                                id:"cancel",
                                value:"取消"
                            },
                            {
                                id:"ok",value:"确定",
                                autofocus:true,
                                callback:function(){
                                    var $form = this.getContent().find('form');
                                    $form.checkForm({
                                        onSuccess:function(){
                                            var data = $form.serialize();
                                            var tmpdata= JSON.stringify(data);
                                            dtd.resolve($.deParam(data))
                                            
                                            idialog.close();
                                        },
                                        onFail:function(e){
                                            alert(e.msg)
                                        }
                                    })
                                    return false;
                                }
                            }
                        ]
                    }).showModal();
                    
                    return dtd;
                },
                getFormData :function(url , data){
                    var dtd = $.Deferred();
					
					var defaultData=
					{
					    "intro":"",
					    "thumb": "0563223058e64235bfd95404dde33b5d",
					    "actionPrizeInformationItems":[
					        {
					            "prizeid":"1",
					            "winningprobability":"20",
					            "info":"test",
					            "winninglimit":"20",
					            "winningnumber":"5",
					            "thumb":"385da4550b324735b8df1e2ae022d672"
					        },
					        {
					            "prizeid":"2",
					            "winningprobability":"20",
					            "info":"test",
					            "winninglimit":"20",
					            "winningnumber":"5",
					            "thumb":"385da4550b324735b8df1e2ae022d672"
					        },
					        {
					            "prizeid":"3",
					            "winningprobability":"20",
					            "info":"test",
					            "winninglimit":"20",
					            "winningnumber":"5",
					            "thumb":"385da4550b324735b8df1e2ae022d672"
					        },
					        {
					            "prizeid":"4",
					            "winningprobability":"20",
					            "info":"test",
					            "winninglimit":"20",
					            "winningnumber":"5",
					            "thumb":"385da4550b324735b8df1e2ae022d672"
					        },
					        {
					            "prizeid":"5",
					            "winningprobability":"20",
					            "info":"test",
					            "winninglimit":"20",
					            "winningnumber":"5",
					            "thumb":"385da4550b324735b8df1e2ae022d672"
					        },
					        {
					            "prizeid":"6",
					            "winningprobability":"20",
					            "info":"test",
					            "winninglimit":"20",
					            "winningnumber":"5",
					            "thumb":"385da4550b324735b8df1e2ae022d672"
					        },
					        {
					            "prizeid":"7",
					            "winningprobability":"20",
					            "info":"test",
					            "winninglimit":"20",
					            "winningnumber":"5",
					            "thumb":"385da4550b324735b8df1e2ae022d672"
					        },
					        {
					            "prizeid":"8",
					            "winningprobability":"20",
					            "info":"test",
					            "winninglimit":"20",
					            "winningnumber":"5",
					            "thumb":"385da4550b324735b8df1e2ae022d672"
					        }
					    ],
					    "actionPrize": {
							"id": 187,
							"name": "“奔跑吧，宝贝”冰雪运动会大转盘抽奖",
							"relation_id": 283,
							"available_times": 300,
							"status": 1,
							"t": 1465805296027,
							"allprizecount": 60,
							"winninglimit": 0
						}
					}
                    if(!isEdit){
                        return dtd.resolve(defaultData);
                    }
                    
					var url = Action.get('form.detail',search.id);
                    $.getJSON(url, data, function(result){
                        var code = result.code;
                        if(code==200){
                        	console.log("data-->",JSON.stringify(result));
                            dtd.resolve(result.data)
                        }else{
                            var msg = result.msg || '数据获取失败！';
                            dtd.reject(msg)
                            
                        }
                    })
                    .fail(function(e, type, msg){
                        console.error(type + msg)
                        dtd.reject(type + msg)
                    })
                    return dtd;
                },
                
                initForm:function(formData){    
                    var app = this;
                    var vueApp = new Vue({
                        el:'#app',
                        data :function(){
                        	return {
                        		list :formData
                        	}
                        },
                        computed:{
                        	form:function(){
                        		return this.list;
                        	},
						    actionPrize:function(){
						    	return this.list.actionPrize
						    },
                            'pageType':function(){
                                return PageType;
                            },
                            'appId':function(){
                                return search.appid;
                            },
						    prizeItem:function(){
						    	return this.list.actionPrizeInformationItems;
						    }
                        },
                        methods:{
                            showItemEditor:function(item){
                                return app.showFieldEditor(item);
                            },
                            editItem:function(item){
                                var that = this;
                                this.showItemEditor(item).then(function(data){
//									that.list = that.list.map(function(item){
//										if(item.id==data.id) return data;
//										return item;
//									})
									
									if(item.prizeid==data.prizeid){
										$.map(data, function(value,index) {
											item[index]=value;
										});
									}
                                    return data;
                                })
                            },
                            
                            showImage:function(img){
                                if(/^(http(s)?|\/\/)/.test(img)) return img;
                                return Action.get('image.show', img)
                            },	
                            
                            getImageConfig:function(value){
    							return {
									name:'thumb',
									checker:{
										iname:'活动图片',
										itip:'请上传活动图片'
									},
									value:value
								}
    						},
    						chooseAction:function(){
    						    var that = this;
    						    app.chooseContentItem().then(function(data){
    						        that.list.actionPrize.relation_info=data.name;
    						        that.list.actionPrize.relation_id=data.id;
    						        that.list.relationid=data.id;
    						    })
    						},
                            save:function(){
//                              app.previewPage('http://admin.jgrm.com/jgrm/template/jiugongge/');
                                var that = this;
                                app.saveForm(that.list)
                                .then(function(res){
                                    app.alert('操作成功！');
                                })
                                .fail(function(msg){
                                    app.alert(msg);
                                })
                            },
                        },
                    })
                },
                
                saveForm:function(data){
                    
                    var app = this;
                    var dtd = $.Deferred();
                    var actionURL = isEdit ? Action.get('form.update', data) : Action.get('form.add');
                    var $form1 = $('form[data-form=one]');
                    
                    $form1.checkForm({promise:true})
                    .then(function(result){
                        $.ajax({
                            url: actionURL,
                            data:JSON.stringify(data),
                            contentType:'application/json',
                            method:'post'
                        })
                        .fail(function(e){
                            dtd.reject(e)
                        })
                    })
                    .fail(function(e){
                        dtd.reject(e)
                    })
                    
                    return dtd;
                },
                
                initAll : function(){
                    XXUpload('[xx-upload]',{size:'750:360'});
                    DateTimePicker('[datepicker]');
                    RichTextEditor('[rteditor]');
    			},
    			
                init : function(){
                    var app = this;
                    app.getFormData()
                    .then(function(data){
                        app.initForm(data);
                        app.initAll();
                    })
                    .fail(function(e){
                        alert(e)
                    })
                }
            }
            App.init();
        })
   </script>
    </body>
</html>